<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 15:57:59
 * @LastEditors: wangming
 * @LastEditTime: 2021-12-06 16:20:09
 * @Description: file content
-->
<route>
{
  "meta":{
    "title":"脚本管理",
    "showMenu":true,
    "serialNum": 40
  }
}
</route>

<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-input
          v-model="queryData.searchKey"
          placeholder="脚本编码或脚本名称"
          clearable
          :maxlength="64"
          prefix-icon="el-icon-search"
        />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="loadData(1, 'search')"
          >查询</el-button
        >
        <el-button @click="handleReset">重置</el-button>
      </el-col>
      <el-checkbox
        style="float: right; margin-right: 10px"
        v-model="queryData.my"
        @change="loadData(1)"
        >查看我的脚本</el-checkbox
      >

      <el-col :span="24" class="mt10">
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'script',
              title: '新建脚本',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importScript',
              title: '导入脚本',
              upload: {
                accept: '.hm_script',
                httpRequest: handleHttpRequest,
              },
            },
            ...(isDefault
              ? [
                  {
                    icon: 'el-icon-folder-add',
                    command: 'folder',
                    title: '新建文件夹',
                  },
                ]
              : []),
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>
    <template
      v-if="folderData && folderData.length > 0 && isDefault && !searchResFlag"
    >
      <div class="mt10" style="height: 1px"></div>
      <el-divider content-position="left">脚本管理</el-divider>
      <el-row :gutter="12">
        <el-col :span="6" v-for="folder in folderData" :key="folder.id">
          <el-card class="folder-card mb10" shadow="hover">
            <div class="folder-content" @click="handleFolderClick(folder)">
              <i class="el-icon-folder"></i>
              <span :title="folder.name" class="folder-title">{{
                folder.name
              }}</span>
            </div>
            <el-dropdown
              class="menu"
              placement="bottom"
              trigger="click"
              size="medium"
              @command="handleFolderCommand($event, folder)"
            >
              <i class="el-icon-more"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <div class="mt10" style="height: 1px"></div>
    <el-divider v-if="searchResFlag" content-position="left">
      <span class="root-link" @click="loadAllData">脚本管理</span>
      <i class="el-icon-arrow-right"></i>
      查询结果（{{ total }}）</el-divider
    >
    <el-divider v-else-if="isDefault" content-position="left"
      >默认（{{ total }}）</el-divider
    >
    <el-divider v-else content-position="left">
      <span class="root-link" @click="loadAllData">脚本管理</span>
      <i class="el-icon-arrow-right"></i>
      {{ currentFolder.name }}
    </el-divider>
    <el-table
      class="mt10"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column prop="code" label="脚本编码" />
      <el-table-column prop="name" label="脚本名称" />
      <el-table-column prop="description" label="脚本描述" />
      <el-table-column prop="contentType" label="脚本来源">
        <template slot-scope="scope">
          {{ scope.row.contentType | scriptSource }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="脚本内容">
        <template slot-scope="scope">
          <el-tag
            class="mr10"
            style="font-weight: bold; color: #333"
            size="medium"
            type="info"
          >
            {{ scope.row.type | scriptType }}
          </el-tag>
          <!-- eslint-disable -->
          <span v-if="scope.row.contentType === 'CODE'">{{
            scope.row.content | scriptDecode | scriptValue(100)
          }}</span>
          <span v-else>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="modifyDate" label="更新时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>

      <el-table-column prop="actions" label="操作" width="240">
        <template slot-scope="scope">
          <template>
            <span class="table-actionItem">
              <el-button type="text" @click="handleEdit(scope.row)"
                >编辑</el-button
              >
            </span>
            <span class="table-actionItem">
              <el-popconfirm
                title="确定要删除脚本吗？"
                placement="top"
                @confirm="handleDelete(scope.row)"
              >
                <el-button class="link-danger" type="text" slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </span>
            <span class="table-actionItem">
              <el-button type="text" @click="handleSetting(scope.row)"
                >调试</el-button
              ></span
            >
            <span class="table-actionItem">
              <el-button type="text" @click="handleMove(scope.row)"
                >移动</el-button
              ></span
            >
            <span class="table-actionItem"
              ><el-button type="text" @click="handleExport(scope.row)"
                >导出</el-button
              ></span
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="tr mt24">
      <x-pagination
        :total="total"
        :pageSize.sync="pageData.pageSize"
        :pageNo.sync="pageData.pageNo"
        @search="loadData"
      />
    </div>
  </div>
</template>

<script>
import ScriptForm from "./__components__/scriptForm";
import MoveForm from "./__components__/moveForm";

import {
  getHmscriptPageList,
  deleteHmscript,
  getHmscriptExport,
  postHmscriptImport,
} from "@/apis/paas/HmScriptController.js";
import {
  getHmscriptfolderPageList,
  deleteHmscriptfolder,
} from "@/apis/paas/HmScriptFolderController.js";
import FolderForm from "./__components__/folderForm";
import stores from "store2";
import { copy, exportAppDataFromJson } from "@/utils/util";
import DropdownButtons from "@/components/DropdownButtons/Index.vue";

const DEFAULT_FOLDER = 1;
export default {
  name: "Script",
  components: {
    DropdownButtons,
  },
  data() {
    return {
      DEFAULT_FOLDER,
      currentFolder: {
        id: DEFAULT_FOLDER,
      },
      folderData: [],
      loading: false,
      queryData: {},
      searchResFlag: false, // 是否查询结果
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
    };
  },
  computed: {
    isDefault() {
      return this.currentFolder.id === DEFAULT_FOLDER;
    },
  },

  created() {
    const {
      currentFolderId,
      currentFolderName,
      searchKey,
      my,
      searchResFlag,
      pageNo,
      pageSize,
    } = this.$route.query;
    this.currentFolder = {
      id: Number(currentFolderId),
      name: currentFolderName,
    };
    this.searchResFlag = searchResFlag === "true";
    this.$set(this.queryData, "searchKey", searchKey);
    this.$set(this.queryData, "my", my === "true");
    if (pageSize) {
      this.pageData.pageSize = Number(pageSize);
    }
    if (pageNo) {
      this.pageData.pageNo = Number(pageNo);
    }
    this.loadData();
    this.loadFolderData();
  },

  methods: {
    loadData(pageNo = this.pageData.pageNo, searchFlag) {
      if (this.searchResFlag) searchFlag = "search";
      if (!this.currentFolder.id) {
        this.currentFolder = {
          id: this.DEFAULT_FOLDER,
        };
      }
      const params = {
        ...this.queryData,
        ...this.pageData,
        folderId: this.currentFolder.id,
        pageNo,
      };
      if (searchFlag === "search") {
        delete params.folderId;
      }
      getHmscriptPageList(params).then((res) => {
        if (res.data.length === 0 && pageNo > 1) {
          this.loadData(pageNo - 1);
          return;
        }
        if (searchFlag === "search") {
          this.searchResFlag = true;
        } else {
          this.searchResFlag = false;
        }

        this.tableData = res.data;
        this.total = res.totalCount;
        this.pageData = {
          pageSize: res.pageSize,
          pageNo: res.pageNo,
        };
        this.$router.replace({
          ...this.$route,
          query: {
            ...this.pageData,
            ...this.queryData,
            searchResFlag: this.searchResFlag,
            currentFolderId: this.currentFolder.id,
            currentFolderName: this.currentFolder.name,
          },
        });
      });
    },
    loadFolderData() {
      getHmscriptfolderPageList({
        pageSize: 10000,
        pageNo: 1,
      }).then((res) => {
        this._folderData = res.data;
        this.folderData = res.data.filter((item) => item.id !== DEFAULT_FOLDER);
      });
    },
    loadAllData() {
      this.searchResFlag = false;
      this.currentFolder = {
        id: this.DEFAULT_FOLDER,
        name: "",
      };
      this.pageData.pageNo = 1;
      this.loadData();
    },
    handleReset() {
      this.queryData = {};
      this.loadData();
    },

    handleFolderClick(folder) {
      this.searchResFlag = false;
      this.currentFolder = folder;
      this.pageData.pageNo = 1;
      this.loadData();
    },
    handleFolderEdit(record) {
      FolderForm.editForm(record).then(() => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    handleFolderCommand(command, record) {
      if (command === "edit") {
        this.handleFolderEdit(record);
      } else if (command === "delete") {
        this.handleFolderDelete(record);
      }
    },

    handleFolderDelete(record) {
      deleteHmscriptfolder([record.id]).then((res) => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },
    handleCreate(command) {
      if (command === "script") {
        ScriptForm.addForm({
          folderId: this.currentFolder.id,
        }).then(async (res) => {
          this.$message.success("新增成功");
          await this.loadData();
        });
      } else if (command === "folder") {
        FolderForm.addForm().then(() => {
          this.$message.success("新增成功");
          this.loadFolderData();
        });
      }
    },

    handleEdit(record) {
      ScriptForm.editForm(record).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },
    handleSetting(record) {
      const { origin, pathname } = window.location;
      window.open(`${origin}${pathname}#/scriptDebug?scriptId=${record.id}`);
    },
    handleDelete(record) {
      deleteHmscript([record.id]).then((res) => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },
    handleMove(record) {
      MoveForm.editForm(record, {
        folderList: this._folderData,
      }).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmscriptExport({
        scriptId: record.id,
      });
      await exportAppDataFromJson({
        data: res,
        key: record.code,
        ext: "hm_script",
      });

      setTimeout(() => {
        this.$message.success("导出成功");
      }, 1500);
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      await postHmscriptImport(formData, { folderId: this.currentFolder.id });
      this.$message.success("导入成功");
      this.loadData(1);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-menu {
  min-width: 100px;
}

.folder-card {
  border: 1px solid #dcdfe6;
  position: relative;
  cursor: pointer;

  ::v-deep .el-card__body {
    padding: 0;

    .folder-content {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 20px;
      box-sizing: border-box;
    }

    .menu {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .el-icon-folder {
      font-size: 38px;
      color: #999;
      margin-right: 10px;
    }

    .el-icon-more {
      font-size: 18px;
      color: #999;
    }

    .folder-title {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.root-link {
  color: #409eff;
  cursor: pointer;
  margin-right: 5px;
  font-weight: bold;
}
</style>
